<?php namespace system\service;
/**
 * 微信处理的公共类
 * Class Wx
 * @package system\service
 */
class Wx {
	protected $message;

	public function __construct() {
		$this->message = $this->getMessage();
	}

	/**
	 * 获取微信服务器发送来的消息
	 * @return \SimpleXMLElement
	 */
	public function getMessage() {
		if ( isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
			$post = $GLOBALS['HTTP_RAW_POST_DATA'];

			return simplexml_load_string( $post, 'SimpleXMLElement', LIBXML_NOCDATA );
		}
	}

	//与微信服务器进行绑定
	public function bind() {
		if ( isset( $_GET["signature"] )
		     && isset( $_GET["timestamp"] )
		     && isset( $_GET["nonce"] )
		     && isset( $_GET["echostr"] )
		) {
			$signature = $_GET["signature"];
			$timestamp = $_GET["timestamp"];
			$nonce     = $_GET["nonce"];
			$token     = c( "wx.token" );
			$tmpArr    = [ $token, $timestamp, $nonce ];
			sort( $tmpArr, SORT_STRING );
			$tmpStr = implode( $tmpArr );
			$tmpStr = sha1( $tmpStr );
			if ( $tmpStr == $signature ) {
				die( $_GET["echostr"] );
			}
		}
	}

	/**
	 * 获取主动消息使用的access_token接口
	 * @param string $name 缓存access_token名子,用于区分多个微信公众号
	 *
	 * @return mixed
	 */
	protected function accessToken($name='access_token') {
		if ( ! $access_token = Cache::get($name ) ) {
			$appid        = c( 'wx.appid' );
			$secret       = c( 'wx.secret' );
			$url          = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
			$d            = Curl::get( $url );
			$d            = json_decode( $d, TRUE );
			$access_token = $d['access_token'];
			Cache::set( $name, $d['access_token'] ,3600);
		}

		return $access_token;
	}

	/**
	 * 实例化出功能类
	 *
	 * @param $name
	 *
	 * @return mixed
	 */
	public function instance( $name ) {
		static $cache = [ ];
		if ( ! isset( $cache[ $name ] ) ) {
			$class          = '\system\service\build\\' . ucfirst( $name );
			$cache[ $name ] = new $class;
		}

		return $cache[ $name ];
	}
}







